package qiongqi

import (
	"io/ioutil"
	"os"
	"path/filepath"
)

type QiongqiEngine struct {
	parser      Parser
	timingStart bool
}

// 初始化引擎
func (e *QiongqiEngine) Init(parser Parser) (*QiongqiEngine, error) {

	e.parser = parser
	return e, nil
}

// loadFile 加载文件数据
func (e *QiongqiEngine) LoadFile(name string) (*ParseResult, error) {
	data, err := e.parseFile(name)
	if err != nil {
		return nil, err
	}
	result, err := e.CreateFlow(data)
	if err != nil {
		return nil, err
	} else {
		return result, err
	}

}

func (e *QiongqiEngine) parseFile(name string) ([]byte, error) {
	fullName, err := filepath.Abs(name)
	if err != nil {
		return nil, err
	}
	file, err := os.Open(fullName)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	data, err := ioutil.ReadAll(file)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (e *QiongqiEngine) CreateFlow(data []byte) (*ParseResult, error) {
	result, err := e.parser.Parse(data)
	if err != nil {
		return nil, err
	} else {
		return result, err
	}
}

func (e *QiongqiEngine) LoadString(content string) (*ParseResult, error) {
	byteContent := []byte(content)
	result, err := e.parser.Parse(byteContent)
	if err != nil {
		return nil, err
	} else {
		return result, nil
	}

}
